package com.imprenta.converter;

import java.util.ArrayList;

import javax.el.ValueExpression;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import com.imprenta.bean.TipoClienteBean;
import com.imprenta.model.TipoClienteBase;

@SuppressWarnings("unused")
public class TipoClienteConverter implements Converter{

	@Override
	//Este metodo convierte el tipoclienteid en una instancia de 
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		if (arg0 == null) { throw new NullPointerException("context"); }
		if (arg1 == null) { throw new NullPointerException("component"); }
		FacesContext ctx = FacesContext.getCurrentInstance();
		ValueExpression vex = ctx.getApplication()
				.getExpressionFactory().createValueExpression(ctx.getELContext(), 
						"#{tipoClienteBean}",TipoClienteBean.class);
		
		TipoClienteBean tcbean = (TipoClienteBean) vex.getValue(ctx.getELContext());
		TipoClienteBase tcp = null;
		try {
			tcp = tcbean.getTipoClienteById(new Integer(arg2));
		} catch (Exception e) {
			// TODO: handle exception
		}
		
//		if (tcp==null ) {
//			FacesMessage message = new FacesMessage(
//					FacesMessage.SEVERITY_ERROR,
//					"Unknown value", "The car is unknown!" );
//					throw new ConverterException( message );
//		}
		return tcp==null? arg2 : tcp;
	}

	@Override
	//Este metodo extrae y retorna el campo tipoclienteid
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		if (arg0 == null) { throw new NullPointerException("context"); }
		if (arg1 == null) { throw new NullPointerException("component"); }
		String result = "";
		try {
			result = ((TipoClienteBase)arg2).getTipoclienteid().toString();// ((TipoClienteBean)arg2).getTipoCliente().toString();
		} catch (Exception e) {
		}
		
		return result;
	}

}
